package com.sendpo.zjx.sendpo.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.UserAddressDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.table.UserAddress;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/8/11.
 */

public class AddressListActivity extends AppCompatActivity {

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    private LinearLayoutManager lm;
    private RecylcerAdaper adpater;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addresslist);
        Tools.initStatus(this, R.color.black);
        ButterKnife.bind(this);
        initComponent();
    }
    private void initComponent() {

        lm=new LinearLayoutManager(this, OrientationHelper.VERTICAL,false);
        recyclerview.setLayoutManager(lm);


    }


    @OnClick(value = {R.id.backbt,R.id.add_address})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.add_address:
                Tools.redirectActivity(this,LocEditManagerActivity.class);
                break;
        }
    }

    public class RecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<UserAddress> addresses;
        public LayoutInflater inflater;

        public RecylcerAdaper(List<UserAddress> addresses, Context context) {
            inflater = LayoutInflater.from(context);
            this.addresses = addresses;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder ih = null;
            ih = new IndexHoler(inflater.inflate(R.layout.listitem_locmanager, parent, false));
            return ih;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            IndexHoler ih = (IndexHoler) holder;
            final UserAddress userAddress=this.addresses.get(position);
            ih.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent data=new Intent();
                    data.putExtra("address_data",userAddress);
                    setResult(RESULT_OK,data);
                    finish();
                }
            });
            ih.rootView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    AlertDialog dialog=new AlertDialog.Builder(AddressListActivity.this)
                            .setNegativeButton("删除地址", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    remove(position);
                                    delete(userAddress.getAddressId()+"");
                                    dialogInterface.dismiss();
                                }
                            }).create();

                    dialog.show();
                    return false;
                }
            });
            ih.name.setText(userAddress.getUserConsignee());
            ih.iphone.setText(userAddress.getUserIphone());
            ih.cityaddress.setText(userAddress.getUserCity()+"  "+userAddress.getUserDetailedAddress());

        }

        @Override
        public int getItemCount() {
            return addresses.size();
        }

        public void initRefresh(List<UserAddress> addresses){
            this.addresses.removeAll(this.addresses);
            this.addresses.addAll(addresses);
            notifyDataSetChanged();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public View rootView;
            public RelativeLayout right;
            public TextView name;
            public TextView iphone;
            public TextView cityaddress;
            public IndexHoler(View itemView) {
                super(itemView);
                rootView = itemView;
                right=itemView.findViewById(R.id.right);
                name=itemView.findViewById(R.id.name);
                iphone=itemView.findViewById(R.id.iphone);
                cityaddress=itemView.findViewById(R.id.cityaddress);
            }
        }

        public void remove(int position){
            this.addresses.remove(position);
            notifyDataSetChanged();
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        query();

    }

    public void query(){
        final List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            return;
        }
        User user = userList.get(0);
        Map<String,String> map=new HashMap<>();
        map.put("userId",user.getUserId()+"");
        Xutils.POST(HttpUrl.useraddressbyid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson=new Gson();
                UserAddressDomain domain= gson.fromJson(result, UserAddressDomain.class);
                switch (domain.state){
                    case HttpCode.SUCCESS:
                        if(domain.getData()!=null&&domain.getData().size()!=0){
                            if(adpater==null){
                                recyclerview.setAdapter(adpater=new RecylcerAdaper(domain.getData(),AddressListActivity.this));
                            }else{
                                adpater.initRefresh(domain.getData());
                            }
                        }
                        break;

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    public void delete(String addressId){
        Map<String,String> map=new HashMap<>();
        map.put("addressId",addressId);
        Xutils.POST(HttpUrl.useraddressremove, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject json=new JSONObject(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
